package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.Manage;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		request.setCharacterEncoding("utf-8");
		String id =  request.getParameter("id");
		String pwd =  request.getParameter("pwd");
		System.out.println(id);
		Manage man = new Manage();
		int waring = 0;
		if("admin".equals(id))
		{
			if("123456".equals(pwd))
			{
				waring = 4;
			}
		}
		else
		{
			try {
				waring = man.Login(id ,pwd);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(waring == 3)
		{
			HttpSession session = request.getSession();
			session.setAttribute("tea_id", id);
		}
		else if(waring == 1)
		{
			HttpSession session = request.getSession();
			session.setAttribute("stu_id", id);
		}
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out= response.getWriter();
			JSONArray jsons=new JSONArray();
			JSONObject json=new JSONObject();
			json.put("waring", waring);
			jsons.add(json);
			System.out.println(jsons.toString());
			out.println(jsons.toString());
			out.flush();
			out.close();
		
	}

}
